<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Zan;
use Illuminate\Http\Request;
use \App\Post;

class PostsController extends Controller
{
    //查看
    public function index()
    {
        $posts = Post::orderBy('created_at', 'desc')->withCount(['comments', 'zans'])->paginate(10);
        return view('post/index', compact('posts'));
    }

    //展示详情页面
    public function show(Post $post)
    {
        $post->load('comments');
        return view('post/show', compact('post'));
    }

    //编辑
    public function edit(Post $post)
    {
        return view('post/edit', compact('post'));
    }

    //创建
    public function create()
    {
        return view('post/create');
    }

    //保存文章
    public function store()
    {
        $this->validate(request(), [
            'title' => 'required|string|max:100|min:10',
            'content' => 'required|string|max:1000|min:10',
        ]);

        $userId = \Auth::id();
        $params = array_merge(request(['title', 'content']), ['user_id' => $userId]);
        $res = Post::create($params);

        dd($res);
    }

    //更新文章
    public function update(Post $post)
    {
        //判断是否有编辑权限
        $this->authorize('update', $post);

        $post->title = request('title');
        $post->content = request('content');
        $post->save();
    }

    //删除文章
    public function delete(Post $post)
    {
        //判断是否有删除权限
        $this->authorize('delete', $post);

        $res = $post->delete();
        if ( $res) return redirect('/posts');
    }

    //评论
    public function comment(Post $post)
    {
        $this->validate(request(), [
            'comment'   => 'required|min:3'
        ]);

        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->post_id = $post->id;
        $comment->content = request('comment');
        $comment->save();

        return back();
    }

    //点赞
    public function zan(Post $post)
    {
        $param = [
            'user_id' => \Auth::id(),
            'post_id'   => $post->id
        ];

        Zan::firstOrCreate($param);

        return back();
    }

    //取消赞
    public function unzan(Post $post)
    {
        $post->zan(\Auth::id())->delete();

        return back();
    }

    //搜索页面
    public function search()
    {
        $this->validate(request(), [
            'query' => 'required'
        ]);

        $query = request('query');
        $posts = Post::search($query)->paginate(1);

        return view('post/search', compact('posts', 'query'));
    }
}
